package com.hck.ch02.demo;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

public class Demo5 {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
        //得到DOM解析的工厂实例
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //从DOM工厂获得DOM解析器
        DocumentBuilder db = dbf.newDocumentBuilder();
        //解析XML文档，得到一个Document对象，即DOM树
        Document doc = db.parse("src\\com\\hck\\ch02\\demo\\Demo2.xml");
        //找到修改的节点
        NodeList list = doc.getElementsByTagName("Brand");
        for (int i = 0; i<list.getLength(); i++){
            Element brandElement = (Element)list.item(i);
            String brandName = brandElement.getAttribute("name");
            if (brandName.equals("三星")){
                brandElement.setAttribute("name","SAMSUNG");//修改属性
            }
        }
    }
}
